package org.theSeed.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.theSeed.base.exp.BuzExp;
import org.theSeed.base.pojo.sysEnum.SysCode;
import org.theSeed.mapper.SysRoleMapper;
import org.theSeed.mapper.SysUserMapper;
import org.theSeed.pojo.dto.UserInfo;
import org.theSeed.pojo.dto.UserInfoUserDetails;
import org.theSeed.pojo.po.SysRole;
import org.theSeed.pojo.po.SysUser;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser userByUsername = sysUserMapper.findUserByUsername(username);
        if (ObjectUtil.isNotNull(userByUsername)){
            List<SysRole> userRoleList = sysRoleMapper.findUserRoleByUserId(userByUsername.getId());
            UserInfo loginInfo = BeanUtil.copyProperties(userByUsername, UserInfo.class);
            List<String> roleCodeList = userRoleList.stream()
                    .map(SysRole::getRoleCode)
                    .collect(Collectors.toList());
            loginInfo.setRoleCodeList(roleCodeList);

            return new UserInfoUserDetails(loginInfo);
        }
        throw new BuzExp(SysCode.FAIL,"用户不存在");
    }
}
